package com.jingbian.cppccbackend.controller.user;

import com.github.pagehelper.PageInfo;
import com.jingbian.cppccbackend.entity.PublicOpinions;
import com.jingbian.cppccbackend.entity.Result;
import com.jingbian.cppccbackend.entity.dto.PublicOpinionPublicDTO;
import com.jingbian.cppccbackend.entity.dto.SearchPublicOpinionDTO;
import com.jingbian.cppccbackend.entity.dto.SubmitPublicOpinionDTO;
import com.jingbian.cppccbackend.service.user.PublicOpinionsService;
import com.jingbian.cppccbackend.utils.ResultUtil;
import com.jingbian.cppccbackend.entity.vo.PublicOpinionDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import org.springframework.core.io.Resource;

/**
 * <p>
 * 社情民意信息表 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-04-26
 */
@RestController
@Validated
@RequestMapping("/users/publicOpinions")
public class PublicOpinionsController {
    @Autowired
    private PublicOpinionsService publicOpinionsService;

    /**
     * 提交社情民意
     * @param submitPublicOpinionDTO 社情民意提交数据
     * @return Result<String>
     */
    @PostMapping("/submitPublicOpinions")
    public Result<String> submitPublicOpinions(@RequestBody @Validated SubmitPublicOpinionDTO submitPublicOpinionDTO) {
        publicOpinionsService.submitPublicOpinions(submitPublicOpinionDTO);
        return ResultUtil.success("社情民意提交成功！");
    }

    /**
     * 获取用户的社情民意列表
     */
    @PostMapping("/list")
    public Result<PageInfo<PublicOpinions>> getPublicOpinionsByUserId(@RequestBody SearchPublicOpinionDTO searchDTO) {
        PageInfo<PublicOpinions> pageInfo = publicOpinionsService.getPublicOpinionsByUserId(searchDTO);
        return ResultUtil.success(pageInfo);
    }


    /**
     * 获取社情民意详情
     */
    @GetMapping("/{opinionId}")
    public Result<PublicOpinionDetailVO> getPublicOpinionDetail(@PathVariable Integer opinionId) {
        PublicOpinionDetailVO detail = publicOpinionsService.getDetailById(opinionId);
        return ResultUtil.success(detail);
    }

    @Transactional
    @PostMapping("/wordCreate/{opinionId}")
    public ResponseEntity<Resource> wordCreate(@PathVariable Integer opinionId) throws IOException {
        PublicOpinionDetailVO request = publicOpinionsService.getDetailById(opinionId);
        String signers = "无";
        if(request.getSignersName()!=null){
            signers = String.join("、", request.getSignersName());
        }
        Map<String, String> data = new HashMap<>();
        // 创建通用时间处理方法
        Function<Object, String> formatTime = time ->
                time != null ?
                        time.toString()
                                .replace("T", " ")      // 替换T为空格
                                .substring(0, 16)       // 截取前16位(2024-12-22 10:00)
                        : "";

        // 填充数据
        data.put("opinionId", request.getOpinionId() != null ? request.getOpinionId().toString() : "");
        data.put("reason", request.getCaseReason() != null ? request.getCaseReason() : "");
        data.put("proposer", request.getProposer() != null ? request.getProposer() : "");
        data.put("region", request.getProposerRegion() != null ? request.getProposerRegion() : "");
        data.put("opinionType", request.getOpinionType() != null ? request.getOpinionType() : "");
        data.put("submitTime", formatTime.apply(request.getSubmitTime()));
        data.put("opinionContent", request.getOpinionContent() != null ? request.getOpinionContent() : "");
        data.put("result", request.getHandingResult() != null ? request.getHandingResult() : "");
        data.put("status", request.getStatus() != null ? request.getStatus() : "");
        data.put("firstAuditTime", formatTime.apply(request.getFirstAuditTime()));
        data.put("recheckTime", formatTime.apply(request.getRecheckTime()));
        data.put("specialHandlingTime", formatTime.apply(request.getSpecialHandlingTime()));
        data.put("finalReplyTime", formatTime.apply(request.getFinalReplyTime()));
        data.put("completionTime", formatTime.apply(request.getCompletionTime()));
        data.put("signers", signers != null ? signers : "");
        data.put("organizerWill", request.getOrganizerWill() != null ? request.getOrganizerWill() : "");
        data.put("public",request.getIsPublic()?"是":"否");
        data.put("topic",request.getTopic()!=null?request.getTopic():"");
        ByteArrayResource resource = publicOpinionsService.generateOpinionDoc(data);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=opinion.docx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body((Resource) resource);
    }

    /**
     * 社情民意公示--含搜索分页查询
     */
    @PostMapping("/getAllPublic")
    public Result<PageInfo<PublicOpinions>> getAllPublicOpinions(@RequestBody PublicOpinionPublicDTO publicOpinionPublicDTO) {
        return ResultUtil.success(publicOpinionsService.getSearchPublic(publicOpinionPublicDTO));
    }


    /**
     * 申请取消已通过初审的社情民意
     * @param opinionId 社情民意id
     * @return Result<String>
     */
    @PutMapping("/applyCancel/{opinionId}")
    public Result<String> applyCancelOpinion(@PathVariable Integer opinionId) {
        Integer cancel = publicOpinionsService.applyCancelOpinion(opinionId);
        if (cancel==1) {
            return ResultUtil.fail("该报送不存在，无法取消！");
        }else if (cancel==2){
            return ResultUtil.fail("非报送人，不可取消！");
        }else if (cancel==3){
            return ResultUtil.success("报送取消申请成功！");
        }else if(cancel==4){
            return ResultUtil.fail("不符合条件,请操作第二个按钮");
        }else {
            return ResultUtil.fail("该报送正在取消中！");
        }
    }
}
